package thread;
/**
 * 线程安全
 */
class Count{
    // 两个线程来同时使这个变量自增
    public int count;
    public synchronized void increase() {
        count++;
    }
}
class A{
    public static int sum;
    public static void increase(){
        synchronized(A.class){
            sum++;
        }
    }
}
public class TestDemo13 {

    public static int sum;
    static Object locker = new Object();

    public void increase(){
        synchronized(this){
            sum++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
                synchronized (locker){
                    sum++;
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
//                synchronized (locker){
//                    sum++;
//                }
                sum++;
            }
        });
        t2.start();
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println(sum);
        System.out.println("计算用时" + (end - begin) + "ms");
    }

    
    public static void main2(String[] args) throws InterruptedException {
        Count count = new Count();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
                count.increase();
                sum++;
            }
        });
        t1.start();

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5_0000; i++) {
                count.increase();
                sum++;
            }
        });
        t2.start();

        t1.join();
        t2.join();// 必须要调用 join,不然两个自增线程和 main线程并发执行
        // count自增的三步指令:
        // 1. 从内存中将count变量取出,加载到 CPU寄存器中
        // 2. 把寄存器的值 +1
        // 3. 将寄存器的值 重新写入内存
        // 在 "抢占式执行 " 的情况下,有很多情况
        System.out.println(count.count);
        System.out.println(sum);
    }
}
